package com.sumer.psychology.common.application;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Cookie;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 查看统计
 * <p/>
 * Created by twer on 15/3/10.
 */
public class ViewerStatisticsFilter implements ContainerRequestFilter {
    private static Logger logger = LoggerFactory.getLogger(ViewerStatisticsFilter.class);
    private static final List<String> AUTHOR_API = Lists.newArrayList(
            "v1/blog/author",
            "v1/microblog/author",
            "v1/photo/author",
            "v1/sharing/author"
    );

    private static final List<String> CONTENT_API = Lists.newArrayList(
            "v1/blog",
            "v1/microblog",
            "v1/photo",
            "v1/sharing"
    );

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        String visitorId = currentUserId(requestContext);
        String visitedId = visitedUserId(requestContext);

        if (notNeededToStatistics(requestContext, visitorId, visitedId)) {
            return;
        }
        ApplicationServiceRegistry.visitStatisticsRepository().add(visitedId, visitorId);
    }

    /*
     * 不需要统计访客的情况
     */
    private boolean notNeededToStatistics(ContainerRequestContext requestContext, String visitorId, String visitedId) {
        return !isGetMethod(requestContext)
                || (!isAuthorApi(requestContext) && !isContentApi(requestContext))
                || StringUtils.isBlank(visitorId)
                || visitorId.equals(visitedId);
    }

    private boolean isContentApi(ContainerRequestContext requestContext) {
        return CONTENT_API.contains(urlPath(requestContext));
    }

    private boolean isAuthorApi(ContainerRequestContext requestContext) {
        return AUTHOR_API.contains(urlPath(requestContext));
    }

    private boolean isGetMethod(ContainerRequestContext requestContext) {
        return requestContext.getMethod().equals(HttpMethod.GET);
    }

    /*
     * url mapping
     */
    private String urlPath(ContainerRequestContext requestContext) {
        String path = requestContext.getUriInfo().getPath();
        return path.substring(0, path.lastIndexOf("/"));
    }

    /*
     * 业务类型
     */
    private String businessType(ContainerRequestContext requestContext) {
        String path = urlPath(requestContext);
        return path.substring(path.indexOf("/") + 1);
    }

    /*
     * 获得当前user id
     */
    private String currentUserId(ContainerRequestContext requestContext) {
        Map<String, Cookie> cookies = requestContext.getCookies();
        Cookie uId = cookies.get("uid");
        Cookie uIdPk = cookies.get("uidpk");
        if (uId != null && uIdPk != null) {
            logger.info("uid: {}", uId.getValue());
            logger.info("uidpk: {}", uIdPk.getValue());
        } else {
            logger.info("uid or uidpk is null");
        }
        logger.info("service: {}", ApplicationServiceRegistry.userService());
        return ApplicationServiceRegistry
                .userService()
                .userId(uId.getValue(), uIdPk.getValue());
    }

    /*
     * 获得被访问者Id
     */
    private String visitedUserId(ContainerRequestContext requestContext) {
        String path = requestContext.getUriInfo().getPath();
        String identity = path.substring(path.lastIndexOf("/") + 1);

        if (isContentApi(requestContext)) {
            identity = ApplicationServiceRegistry
                    .commonQueryApplicationService()
                    .author(businessType(requestContext), identity);
        }
        return identity;
    }

}
